<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Timesheet extends User_Controller
{
	private $response = array();
	private $userModel;
	private $clientModel;
	private $timesheetModel;
	private $requestManager;
	private $payrollModel;
	private $settings;
    public function __construct()
    {
        parent::__construct();
        $this->userModel = $this->load->model('User_Model');
        $this->clientModel = $this->load->model('Client_Model');
        $this->timesheetModel = $this->load->model('Timesheet_Model');
        $this->payrollModel = $this->load->model('Payroll_Model');
        $this->load->helper('RequestManager');
        $this->requestManager = RequestManager::getInstance();
        $this->settings = $this->config->item('settings');
    }
	
	public function payroll_period($api,$payroll_period_id){
		$data = array();
		$result = $this->timesheetModel->getLogsByPeriod($api, $payroll_period_id);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		$this->load->view('index', $data);
	}
	
	public function summary_period($api,$payroll_period_id){	
		
		$data = array();
		$result = $this->timesheetModel->getLogsByPeriodSummary($api, $payroll_period_id);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		
		$this->load->view('index', $data);
	}
	
	public function summary_payroll($api,$payroll_period_id){	
		$data = array();
		$result = $this->timesheetModel->getLogsForPayroll($api, $payroll_period_id);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		
		$this->load->view('index', $data);
	}
	
	public function load($api){
		require_once $_SERVER['DOCUMENT_ROOT'].'/application/managers/Excel_Reader.php';
		$this->load->helper('StringUtils');
		$data = array();
		$excel = Excel_Reader::getInstance();
		$excel->setFilename($_SERVER['DOCUMENT_ROOT'] ."/timesheets/goji.xls");
		$data = $excel->read();
		$sheets = $data->sheets;
		$items = $sheets[0]['cells'];
		//echo $data;
		$client = $this->clientModel->find($api);
		//var_dump($client);
		$names = array();
		$member_name = "";
		
		foreach ($items as $item){
			
			if(strtolower($item[1]) == 'staff no.') {
				$username = strtolower(StringUtils::addUnderscore($item[5]));
				$filter = array('client_id'=>$client->id, 'username'=>$username);
				$user = $this->userModel->find($filter);
				$member_name = $user[0]->username;
				$names["$member_name"]["user_id"] = $user[0]->id;
				continue;
			} else if (strtolower($item[1])== "staff summary") {
				$names["$member_name"]['summary'] = $item;
				continue;
			} else if (strtolower($item[1])== "dept. summary") {
				$names["department"]['summary'] = $item;
				break;
			} else if(substr($item[1], 0, 4)== '2012') {
				//echo "adfasd";
				if($member_name != ""){
					$names["$member_name"]['logs'][] = $item;
				}
				//array_push($names["$member_name"]['logs'], $item);
				//$names["$member_name"]['logs'][count($names["$member_name"]['logs'])] = $item;
				continue;
			}
			

		}
		
		
		foreach($names as $key=>$name){
			if(isset($name["user_id"])){
				
			} else {
				continue;
			}
			
			$user_id = $name["user_id"];
			$logs = $name["logs"];
			$summary = $name["summary"];
			echo "<p style='background-color:#f00'>Name: " . $key." ($user_id)</p>";
			
			foreach ($logs as $log) {
				$param = array();
				$date = substr(trim($log[1]),0,10);
				if(isset($log[6])) $ot = trim($log[6]);
				
				$time = (trim($log[3])!= "")?explode("  ", trim($log[3])):'';
				$absent = trim($log[9]);
				$late = trim($log[10]);
				$out_early = trim($log[11]);
				$early = trim($log[12]);
				if(isset($log[15])) 
					$remark = 	trim($log[15]);
				else 
					$remark = "";

				if($time != ''){
					if(count($time) == 2) {
						//echo "time in: " .$time[0].'<br>';
						//echo "time out: " .$time[1].'<br>';
						$param['time_in'] = "$date {$time[0]}";
						$param['time_out'] = "$date {$time[1]}";
					} else if (count($time) == 1){
						list($hr, $min) = explode(":",$time[0]);
						if(intval($hr) < 12 ) {
							//echo "time in: " .$time[0].'<br>';
							$param['time_in'] = "$date {$time[0]}";
							//echo "time out: -- <br>";
						} else {
							//echo "time in: -- <br>";
							//echo "time out: " .$time[0].'<br>';
							$param['time_out'] = "$date {$time[0]}";
						}
					}
				}

				//echo "absent: $absent <br>";
				//echo "late: $late <br>";
				//echo "out_early: $out_early <br>";
				//echo "early: $early <br>";
				//echo "remark: $remark <br>-------------------<br><br>";
				
				$param['date'] = $date;
				//$param['absent']=  $absent;
				$late .= ($late != '')?":00":'00:00:00';
				$param['late'] = $late;
				$out_early .= ($out_early != '')?":00":'00:00:00';
				$param['undertime'] = $out_early;
				$early .= ($early != '')?":00":'00:00:00';
				$param['earlier'] = $early;
				
				switch(strtolower($remark)){
					case 'absent':
						$remark_id = 1;
						break;
						
					case 'leave with pay':
						$remark_id = 2;
						break;
					
					case 'leave w/o pay':
						$remark_id = 3;
						break;
				
					case 'day off':
						$remark_id = 4;
						break;
						
					case 'wrong card':
						$remark_id = 5;
						break;
					
					case 'adjusted':
						$remark_id = 6;
						break;
						
					default:
						$remark_id = 7;
						break;
				}
				$param['remarks'] = $remark_id;
				$param['user_id'] = $user_id;
				
				
				
				var_dump($param);
				// $timesheet_id = $this->timesheetModel->save($param);
				
				echo "<br>************************************<br>";
				
				
			}
			
			//echo $user_id ."<br>";
			//if(isset($name["logs"])){
				
				//echo $user_id ."<br>";
			//	var_dump($logs);
			//	echo "<br>";
			//}
			
			//echo $name["id"];
			//$logs = $name["logs"];
			//$user_id = $name->id;
			//$logs = $name['logs'];
		}
		
		
		/*
		foreach ($names as $member) {
			$username = strtolower(StringUtils::addUnderscore($member['name']));
			$password = "test";
			$this->requestManager->setData(array('username'=>$username,'password'=>$password));
			$this->requestManager->setSendType("rest");
			$this->requestManager->setAccessPath($this->settings['api_path']."user/register/" .$this->settings['client_key']);
			$return = $this->requestManager->send();
			if($return->message == "success"){
				$params = array('user_id'=>$return->data->user_id, 'first_name'=>$member['name'],'employee_id'=>$member['id']);
				$this->requestManager->setData($params);
				$this->requestManager->setSendType("post");
				$this->requestManager->setAccessPath($this->settings['api_path']."user/file201/" .$this->settings['client_key']);
				$return = $this->requestManager->send();
			} else {
				return;
			}
			
		}
		*/
		
		//var_dump($names);
	}
	
	public function view_user($api,$payroll_period_id,$user_id){
		$data = array();
		$result = $this->timesheetModel->getLogsByPeriodByUser($api, $payroll_period_id, $user_id);
		$payroll = $this->payrollModel->getPayrollPeriod($api,$payroll_period_id);
		$rest_day = $this->userModel->getUserRestDay($api,$user_id);
		$timesheet_payroll = $this->payrollModel->userPayroll($api, $payroll_period_id, $user_id);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			$response["period"] = $payroll;
			$response["rest_day"] = $rest_day;
			$response["timesheet_payroll"] = !empty($timesheet_payroll);
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		$this->load->view('index', $data);
	}
	
	public function view($api, $payroll_period_id=0){
		$data = array();
		$result = $this->payrollModel->getAllPayrollPeriods($api, $payroll_period_id);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		$this->load->view('index', $data);
	}
	
	public function details($api,$user_id,$timesheet_id){
		$result = $this->timesheetModel->find($api,$user_id,$timesheet_id);
		if(isset($result) && is_array($result) ){
			$client_settings = $this->clientModel->getSettings($api);
			$extra_timesheet = $this->timesheetModel->computeTimesheetPerId($result[0]);
			$response["message"] = "success";
			$response["data"] = $result;
			$response["setting"] = $client_settings[0];
			$response["extra_timesheet"] = $extra_timesheet;
			$response["rest_day"] = $this->userModel->getUserRestDay($api,$user_id);
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		$this->load->view('index', $data);
	}
	
	public function update($api){
		$data = array();
		$result = $this->timesheetModel->update($api, $this->input->post());
		if($result == true){
			$response["message"] = "success";
			$response["data"] = $result;
			$data["response"] = ObjectUtils::arrayToJSON($response);
		}
		
		$this->load->view('index', $data);
	}
	
}